﻿using DMTroube_ZeKer.Model;
using Microsoft.Web.WebView2.WinForms;
using Model.Msg;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DMTroube_ZeKer.Control
{
    public partial class MainWebView : UserControl
    {
        public WebView2? webView2;
        public string _url = "";
        /// <summary>
        /// 当前网址
        /// </summary>
        public string? Url
        {
            get
            {
                return _url;
            }
            set
            {
                webView21.CoreWebView2.Navigate(value);
            }
        }
        public event Action<object?, Microsoft.Web.WebView2.Core.CoreWebView2NavigationStartingEventArgs>? NavigateStarting;
        public event Action<object?, ResultAnalysisInfo>? PinLunInfo;
        public event Action<object?, ResultAnalysisInfo>? LwInfo;
        public event Action<object?, ResultAnalysisInfo>? LikeInfo;
        
        public MainWebView()
        {
            InitializeComponent();
            Init();
        }
        private async void Init()
        {
            await webView21.EnsureCoreWebView2Async();
            webView2 = webView21;
            webView21.CoreWebView2.Navigate("https://live.douyin.com/");
            webView21.CoreWebView2.NavigationStarting += CoreWebView2_NavigationStarting;
            webView21.CoreWebView2.DOMContentLoaded += CoreWebView2_DOMContentLoaded;
            webView21.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;
        }

        private void CoreWebView2_WebMessageReceived(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2WebMessageReceivedEventArgs e)
        {
            string resultJson = e.WebMessageAsJson.Trim('"').Replace("\\\"", "\"").Replace("\\\\\"", "'");
            Controller.InfoAnalysis.init(resultJson, PinLunInfo, LwInfo, LikeInfo);
        }

        private void CoreWebView2_NavigationStarting(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationStartingEventArgs e)
        {
            _url = e.Uri.ToString();
            NavigateStarting?.Invoke(sender, e);
        }

        private async void CoreWebView2_DOMContentLoaded(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2DOMContentLoadedEventArgs e)
        {
            string nationJs = Resource.changenation;
            await Task.Delay(1000);
            await webView21.CoreWebView2.ExecuteScriptAsync(nationJs);
        }
        public async void GetDm()
        {
            string observer = Resource.observerpinlun;
            await webView21.CoreWebView2.ExecuteScriptAsync(observer);
        }
    }
}
